package com.personal.system.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.personal.common.result.Result;
import com.personal.system.domain.test.TcGasSaleQuotation;
import com.personal.system.domain.test.TcGasSaleQuoteDetail;
import com.personal.system.entity.approval.AuditRule;
import com.personal.system.entity.approval.AuditRuleDetail;
import com.personal.system.mapper.act.AuditRuleDetailMapper;
import com.personal.system.mapper.act.AuditRuleMapper;
import com.personal.system.mapper.test.TcGasSaleQuoteDetailMapper;
import com.personal.system.service.test.TcGasSaleQuotationService;
import com.personal.system.utils.ConstantPropertiesUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Controller
//@RequestMapping("/wx")
@RequestMapping("/webSocket")
public class WeiXinApiController {

    /**
     * 获取微信登录参数
     */
    @GetMapping("/getLoginParam")
    @ResponseBody
    public Result getLoginParam(HttpSession session) throws UnsupportedEncodingException {
//        String redirectUri = URLEncoder.encode(ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL, "UTF-8");
        String redirectUri = URLEncoder.encode(ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL, "utf-8");
        Map<String, Object> map = new HashMap<>();
        map.put("appid", ConstantPropertiesUtil.WX_OPEN_APP_ID);
        map.put("redirect_uri", redirectUri);
        map.put("scope", "snsapi_login");
        map.put("state", System.currentTimeMillis()+"");

        return Result.ok(map);
    }

    @Resource
    private TcGasSaleQuotationService quotationService;
    @Resource
    private TcGasSaleQuoteDetailMapper quoteDetailMapper;

    @GetMapping("/test")
    public Result test() {

        List<TcGasSaleQuotation> quotations = quotationService.list();

        for (TcGasSaleQuotation quotation : quotations) {
            List<String> audits = Lists.newArrayList();

            Long quoteId = quotation.getQuoteId();
            String quoteNo = quotation.getQuoteNo();
            List<TcGasSaleQuoteDetail> detailList = quoteDetailMapper.selectList(Wrappers.lambdaQuery(TcGasSaleQuoteDetail.class).eq(TcGasSaleQuoteDetail::getQuoteId, quoteId));
            for (TcGasSaleQuoteDetail detailVo : detailList) {
                String begSupplyDate = DateUtil.format(detailVo.getBegSupplyDate(), "yyyy-MM-dd HH:mm:ss");
                Map map = MapUtil.builder(new HashMap<String, Object>())
                        .put("compId", quotation.getCompId()).put("clientId", quotation.getClientId())
                        .put("srcId", detailVo.getSrcId())
                        .put("stationId", detailVo.getStationId()).put("tradeMode", detailVo.getTradeMode())
                        .put("begSupplyDate", begSupplyDate)
                        .put("supplyDate", begSupplyDate.replace("00:00:00", "23:59:59"))
                        .build();
                // 常规毛利
                BigDecimal calcAvg = quoteDetailMapper.getCalcgrassAvg7(map);
                log.info(detailVo.getQuoteDetId() + " 近7天常规毛利：{}", JSON.toJSONString(calcAvg));
                double subtract = detailVo.getCalcGrass().doubleValue();
                // 常规毛利*0%
                double c0 = calcAvg.multiply(BigDecimal.valueOf(0)).doubleValue();
                // 常规毛利*80%
                double c80 = calcAvg.multiply(BigDecimal.valueOf(0.8)).doubleValue();
                // 常规毛利*200%
                double c200 = calcAvg.multiply(BigDecimal.valueOf(2)).doubleValue();

                /** 3.走09审批》常规毛利*80%<= 测算毛利 <常规毛利*200%,无需审批;*/
                if (c80 <= subtract && subtract < c200) {
                    audits.add("09");
                }

                /** 4.走10审批》常规毛利*0%<= 测算毛利 <常规毛利*80%
                 * 或者常规毛利*200%<= 测算毛利，一级审批,区域销售群召集人 */
                if ((c0 <= subtract && subtract < c80) || (c200 <= subtract)) {
                    audits.add("10");
                }

                /*** 5.走11审批》（测算毛利 <0,走二级审批,区域销售群召集人审批后自取组织一号位审批 */
                if (subtract < 0) {
                    audits.add("11");
                }
            }

            List<String> disList = audits.stream().distinct().collect(Collectors.toList());
            Collections.reverse(disList);

            if ((disList.size() == 1 && disList.get(0).equals("09")) || !disList.contains("09")) continue;

            if (disList.get(0).equals("09"))
                quoteDetailMapper.addQuoteTest(quoteId,quoteNo, String.join(",",disList));

        }

        return Result.ok();
    }

    @Resource
    AuditRuleMapper ruleMapper;
    @Resource
    AuditRuleDetailMapper detailMapper;

    @ResponseBody
    @GetMapping("/jsonToSql")
    public Result jsonToSql(String json) {

//        ObjectMapper objectMapper = new ObjectMapper();
////        AuditRule audit = objectMapper.readValue(json, AuditRule.class);
//        List<AuditRule> auditRules = JSONObject.parseArray(json, AuditRule.class);
//
//        AuditRule auditRule = JSONUtil.toBean(json, AuditRule.class);
//
////        String str = JSONUtil.toJsonStr(auditRule);
//
//        List<AuditRule> auditRules1 = JSONUtil.toList(json, AuditRule.class);
//        for (AuditRule auditRule : auditRules) {
//            ruleMapper.insert(auditRule);
//            List<AuditRuleDetail> auditRuleDetails = auditRule.getAuditRuleDetails();
//            for (AuditRuleDetail auditRuleDetail : auditRuleDetails) {
//                auditRuleDetail.setRuleDetailId(UUID.fastUUID().toString(true));
//                detailMapper.insert(auditRuleDetail);
//            }
//        }

        return Result.ok();
    }

    @ResponseBody
    @GetMapping("/airApp")
    public Result airApp() {

        String a12 = "(承运|客户)承担>=气差量,(客户|供应商)及公司不承担";
        String a13 = "(客户|供应)承担>=气差量,(承运商|客户)及公司不承担";
        String a14 = "客户及(承运商|供应商)均承担,公司不承担";
        String a15 = "客户及(承运商|供应商)均不承担,公司承担";
        String a16 = "(承运商|客户)承担< 气差量,(客户|供应商)不承担,公司承担";
        String a17 = "(客户|供应商)承担< 气差量,(承运商|客户)不承担,公司承担";
        String a18 = "(承运商|供应商)客户及公司全部承担";

        List<String> audits = Arrays.asList("12-(承运|客户)承担>=气差量,(客户|供应商)及公司不承担",
                "13-(客户|供应)承担>=气差量,(承运商|客户)及公司不承担",
                "14-客户及(承运商|供应商)均承担,公司不承担",
                "15-客户及(承运商|供应商)均不承担,公司承担",
                "16-(承运商|客户)承担< 气差量,(客户|供应商)不承担,公司承担",
                "17-(客户|供应商)承担< 气差量,(承运商|客户)不承担,公司承担",
                "18-(承运商|供应商)客户及公司全部承担");
        List<String> type = Arrays.asList("02", "04");
        List<String> bear = Arrays.asList("191", "192", "193");

        List<String> yunS = Arrays.asList("577F30A01EB13DFD42DA77C65D6A27B7","BFF57E635C2321AB5330346214E6AEFA");// guosi456/guosicc2
        List<String> keS = Arrays.asList("8F810868C3824B9C1E1872731A2E7CBF","C9F918924D3B8BE064D0806C32B451A3");// cctest1/ceshi0005
        List<String> gongS = Arrays.asList("0539BEB46EB8FB8FC3336AE683E0B933","6900586DB2CDB1F24132601386979656");// yexu01/yexu02

        List<String> sub =Arrays.asList("8F810868C3824B9C1E1872731A2E7CBF","C9F918924D3B8BE064D0806C32B451A3","BFF57E635C2321AB5330346214E6AEFA");

        for (String audit : audits) {
            String[] split = audit.split("-");
            for (String ty : type) {
                for (String be : bear) {
                    String uuid = UUID.fastUUID().toString(true);
                    AuditRule auditRule = new AuditRule();
                    auditRule.setRuleId(uuid);
                    auditRule.setRuleName(split[1]);
                    String yyyyMMdd = DateUtil.format(new Date(), "yyMMdd") + RandomUtil.randomNumbers(5);
                    auditRule.setRuleNo("L"+ yyyyMMdd);
                    auditRule.setCompId("F0AAD515D952B6649AC44BBD629BE28F");
                    auditRule.setCompName("新奥能源贸易有限公司");
                    auditRule.setApprovalModule("04");
                    auditRule.setRuleClass("19");
                    auditRule.setAuditType(split[0]);
                    auditRule.setFeeType(ty);
                    auditRule.setBearType(be);
                    auditRule.setApprovalCriteria("");
                    auditRule.setIsDelete("00");
                    auditRule.setCreateUser("54818E2B4CB004706B7FA4F5CD10A432");
                    auditRule.setCreateTime(new Date());
                    auditRule.setAuditSubmitUser("8F810868C3824B9C1E1872731A2E7CBF,C9F918924D3B8BE064D0806C32B451A3,BFF57E635C2321AB5330346214E6AEFA");

                    ruleMapper.insert(auditRule);

                    if (be.equals("191")){
                        int sort = 1;
                        for (String yun : yunS) {
                            AuditRuleDetail detail = new AuditRuleDetail();
                            String did = UUID.fastUUID().toString(true);
                            detail.setRuleDetailId(did);
                            detail.setRuleId(uuid);
                            detail.setProcessType("02");
                            detail.setRoleType("01");
                            detail.setRole(yun);
                            detail.setDepartment(yun);
                            detail.setSort(sort);
                            detail.setCreateTime(new Date());
                            detailMapper.insert(detail);
                            if (sort == 1) {
                                for (String su : sub) {
                                    String uid = UUID.fastUUID().toString(true);
                                    detail.setRuleDetailId(uid);
                                    detail.setProcessType("01");
                                    detail.setDepartment(su);
                                    detail.setRole(su);
                                    detailMapper.insert(detail);
                                }
                            }
                            sort++;
                        }
                    } else if (be.equals("192")){
                        int sort2 = 1;
                        for (String ke : keS) {
                            AuditRuleDetail detail = new AuditRuleDetail();
                            String did = UUID.fastUUID().toString(true);
                            detail.setRuleDetailId(did);
                            detail.setRuleId(uuid);
                            detail.setProcessType("02");
                            detail.setRoleType("01");
                            detail.setRole(ke);
                            detail.setDepartment(ke);
                            detail.setSort(sort2);
                            detail.setCreateTime(new Date());
                            detailMapper.insert(detail);
                            if (sort2 == 1) {
                                for (String su : sub) {
                                    String uid = UUID.fastUUID().toString(true);
                                    detail.setRuleDetailId(uid);
                                    detail.setProcessType("01");
                                    detail.setDepartment(su);
                                    detail.setRole(su);
                                    detailMapper.insert(detail);
                                }
                            }
                            sort2++;
                        }
                    } else if (be.equals("193")){
                        int sort3 = 1;
                        for (String gong : gongS) {
                            AuditRuleDetail detail = new AuditRuleDetail();
                            String did = UUID.fastUUID().toString(true);
                            detail.setRuleDetailId(did);
                            detail.setRuleId(uuid);
                            detail.setProcessType("02");
                            detail.setRoleType("01");
                            detail.setRole(gong);
                            detail.setDepartment(gong);
                            detail.setSort(sort3);
                            detail.setCreateTime(new Date());
                            detailMapper.insert(detail);
                            if (sort3 == 1) {
                                for (String su : sub) {
                                    String uid = UUID.fastUUID().toString(true);
                                    detail.setRuleDetailId(uid);
                                    detail.setProcessType("01");
                                    detail.setDepartment(su);
                                    detail.setRole(su);
                                    detailMapper.insert(detail);
                                }
                            }
                            sort3++;
                        }
                    }

                }
            }
        }


        return Result.ok();
    }

}
